/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.parameter_name;

import moved.org.objectweb.asm.ClassVisitor;
import moved.org.objectweb.asm.MethodVisitor;
import moved.org.objectweb.asm.Opcodes;
import picounit.features.classloader.NullVisitor;

public class MethodParameterNameClassVisitor extends NullVisitor implements ClassVisitor {
	private final MethodParameterNameMethodVisitor methodParameterNameMethodVisitor;

	private String className;

	public MethodParameterNameClassVisitor(MethodParameterRegistry methodParameterRegistry) {
		this(new MethodParameterNameMethodVisitor(
			new DefaultMethodParameterListener(methodParameterRegistry)));
	}

	public MethodParameterNameClassVisitor(
		MethodParameterNameMethodVisitor methodParameterNameCodeVisitor) {

		this.methodParameterNameMethodVisitor = methodParameterNameCodeVisitor;
	}

	@Override
	public void visit(int version, int access, String className, String signature, String superName,
		String[] interfaces) {

		this.className = className.replace('/', '.');
	}

	@Override
	public MethodVisitor visitMethod(int access, String name, String desc, String signature,
		String[] exceptions) {

		if (isPrivate(access) || isStatic(access)) {
			return NullVisitor.INSTANCE;
		}
		else {
			return methodParameterNameMethodVisitor.visit(className, name, desc);
		}
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// Implementation
	///////////////////////////////////////////////////////////////////////////////////////////////

	private boolean isPrivate(int access) {
		return matchesMask(access, Opcodes.ACC_PRIVATE);
	}

	private boolean isStatic(int access) {
		return matchesMask(access, Opcodes.ACC_STATIC);
	}

	private boolean matchesMask(int access, int mask) {
		return (access & mask) != 0;
	}
}
